<template>
  <div>
    <!-- 标题 -->
    <el-card class="content scrollbar">
      <el-form class="search ml20" :inline="true" label-suffix="：" size="mini">
        <!-- <el-form-item label="账号">
          <el-input v-model="search.loginname" clearable class="w150" placeholder="请输入账号名称" />
        </el-form-item> -->
        <el-form-item label="账号名称">
          <el-input
            v-model="search.name"
            clearable
            class="w150"
            placeholder="请输入账号名称"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="search.tel"
            clearable
            class="w130"
            placeholder="请输入手机号"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="创建日期">
          <el-date-picker
            v-model="searchTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            class="w220"
            clearable
            @change="(val) => changeDateRange( val)"
          />
        </el-form-item>
        <el-form-item label="所属角色">
          <el-input
            v-model="search.rolename"
            clearable
            class="w130"
            placeholder="请输入所属角色"
            @keyup.enter.native="getList('search')"
          />
        </el-form-item>
        <el-form-item label="所属组织">
          <el-cascader
            ref="deptIds"
            v-model="search.deptids"
            class="w180"
            collapse-tags
            :options="options.dept"
            :show-all-levels="false"
            :props="optionProps"
            clearable
            @change="getList('search')"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="search.state " class="w100" placeholder="请选择状态" @change="getList('search')">
            <el-option v-for="item in options.state" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="可登录本系统">
          <el-select v-model="search.isDrugLogin " class="w100" placeholder="请选择是否可登录本系统" @change="getList('search')">
            <el-option v-for="item in options.isDrugLoginOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList('search')">确认
          </el-button>
          <el-button @click="searchReset">重置
          </el-button>
        </el-form-item>
        <el-form-item class="ml50">
          <el-button v-if="permission['001007013002']" type="primary" @click="detailBtn('新增',{})">新增
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="dragTable"
        v-loading="loading"
        :height="tableHeight"
        :data="list"
        size="small"
        :cell-style="$style.cellStyle"
        :header-cell-style="$style.rowClass"
      >
        <ElTableColumn label="ID" type="index" width="50" />
        <ElTableColumn label="账号" prop="loginname" width="100" />
        <ElTableColumn label="姓名" prop="name" width="100" />
        <ElTableColumn label="手机号" prop="tel" width="100" />
        <ElTableColumn label="所属组织" prop="groupName" min-width="200" />
        <ElTableColumn label="所属角色" prop="roleName" width="100" />
        <!-- <ElTableColumn label="所属组织">
          <template slot-scope="{ row }">
            <div v-if="row.deptName.length<=2">
              <span v-for="(item, index) in row.deptName" v-show="index<2" :key="item">
                <span v-if="row.deptName.length-1 == index">{{ item }}</span>
                <span v-else>{{ item + '，' }}</span>
              </span>
              <span>{{ row.deptName.length>2?'...':'' }}</span>
            </div>
            <el-popover v-else placement="top-start" trigger="hover" :content="row.deptName.toString() ">
              <el-button slot="reference" size="mini" type="text">
                <span v-for="(item, index) in row.deptName" v-show="index<2" :key="item">
                  <span v-if="row.deptName.length-1 == index">{{ item }}</span>
                  <span v-else>{{ item + '，' }}</span>
                </span>
                <span>{{ row.deptName.length>=2?'...':'' }}</span>
              </el-button>
            </el-popover>
          </template>
        </ElTableColumn>
        <ElTableColumn label="所属角色">
          <template slot-scope="{ row }">
            <div v-if="row.roleName.length<=2">
              <span v-for="(item, index) in row.roleName" v-show="index<2" :key="item">
                <span v-if="row.roleName.length-1 == index">{{ item }}</span>
                <span v-else>{{ item + '，' }}</span>
              </span>
              <span>{{ row.roleName.length>2?'...':'' }}</span>
            </div>
            <el-popover v-else placement="top-start" trigger="hover" :content="row.roleName.toString() ">
              <el-button slot="reference" size="mini" type="text">
                <span v-for="(item, index) in row.roleName" v-show="index<2" :key="item">
                  <span v-if="row.roleName.length-1 == index">{{ item }}</span>
                  <span v-else>{{ item + '，' }}</span>
                </span>
                <span>{{ row.roleName.length>2?'...':'' }}</span>
              </el-button>
            </el-popover>
          </template>
        </ElTableColumn> -->
        <ElTableColumn label="是否允许登录本系统" min-width="100">
          <template slot-scope="{ row }">
            <span v-if="row.isDrugLogin">允许</span>
            <span v-else>不允许</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态" width="80">
          <template slot-scope="{ row }">
            <span v-if="row.state == 1">启用</span>
            <span v-if="row.state == 0">禁用</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建人" prop="createrName" />
        <ElTableColumn label="创建日期" prop="createTime" width="140" />
        <ElTableColumn label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-dropdown @command="(command)=>{handleCommand(command, scope.row)}">
              <span class="el-dropdown-link">
                <i class="el-icon-more" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="permission['001007013003']" command="修改">修改</el-dropdown-item>
                <!-- <el-dropdown-item
                  v-if="(scope.row.state == 1)&&permission['001007013004']"
                  command="禁用"
                >禁用</el-dropdown-item>
                <el-dropdown-item v-else-if="permission['001007013005']" command="启用">启用</el-dropdown-item> -->
                <el-dropdown-item v-if="permission['001007013006']" command="删除">删除</el-dropdown-item>
                <el-dropdown-item v-if="permission['001007013007']" command="详情">详情</el-dropdown-item>
                <el-dropdown-item v-if="!scope.row.isCheckUnknownDevice" command="开启">开启</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.isCheckUnknownDevice" command="关闭">关闭</el-dropdown-item>
                <el-dropdown-item v-if="permission['001007013008']" command="重置密码">重置密码</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <!-- <el-button type="primary" size="mini" @click="detailBtn('新增部门',row)">新增</el-button>
            <el-button type="primary" size="mini" @click="detailBtn('修改',row)">修改</el-button> -->
          </template>
        </ElTableColumn>
      </el-table>
      <pagination
        class="page tc mt10"
        :total="page.total"
        :page.sync="page.pageNum"
        :limit.sync="search.pageSize"
        @pagination="getList('page')"
      />
      <el-dialog
        v-dialogdrag
        :title="dialogTit"
        :close-on-click-modal="false"
        :visible.sync="dialogVisible"
        width="30%"
      >
        <el-form
          ref="detail"
          :model="detail"
          class="search ml20"
          :inline="true"
          label-position="right"
          :rules="rules"
          label-width="140px"
          size="mini"
        >
          <el-form-item label="账号密码" prop="passwd">
            <el-input
              ref="passwd"
              v-model="detail.passwd"
              class="w300"
              name="passwd"
              placeholder="请输入8-12位字母+数字组合密码"
              :type="passwordType"
            />
            <div class="show-pwd" @click="showPwd('passwd')">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </div>
          </el-form-item>
          <el-form-item label="重复输入密码" prop="rePasswd">
            <el-input
              ref="rePasswd"
              v-model="detail.rePasswd"
              class="w300"
              name="rePasswd"
              placeholder="请输入8-12位字母+数字组合密码"
              :type="passwordType"
            />
            <div class="show-pwd" @click="showPwd('rePasswd')">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
          <el-button size="mini" type="primary" @click="createDetail('detail')">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>

</template>

<script>
import pagination from '@/components/Pagination';
import { getDeptTree } from '@/api/organization';
import { userList, enableUser, deleteUser, resetUserPasswd, updateCheckDevice } from '@/api/account';
import index from '@/mixins/index';
import { mapGetters } from 'vuex';

class Page {
  total = 0;
  pageNum = 1;
}
class Search {
  promotionCard = '';
  name = '';
  tel = '';
  state = '';
  rolename = '';
  deptids = [];
  start_time = '';
  end_time = '';
  pageSize = 30;
}
class Detail {
  passwd = '';
  rePasswd = '';
  userId = '';
}
class Rules {
  passwd = [{ required: true, message: '请填写账号密码', trigger: 'blur' }];
  rePasswd = [{ required: true, message: '请确认账号密码', trigger: 'blur' }];
}
class Options {
  dept = []
  options = [
    { id: 1, name: '选项一' },
    { id: 2, name: '选项二' },
    { id: 3, name: '选项三' },
    { id: 4, name: '选项四' }
  ];
  state = [
    { id: '', name: '全部' },
    { id: 1, name: '启用' },
    { id: 0, name: '禁用' }
  ];
  isDrugLoginOptions = [
    { id: '', name: '全部' },
    { id: 1, name: '允许' },
    { id: 0, name: '不允许' }
  ];
}
export default {
  components: {
    pagination

  },
  mixins: [index],
  data() {
    return {
      search: new Search(), // 检索条件
      options: new Options(), // 选项
      page: new Page(), // 分页
      detail: new Detail(), // 提交信息
      rules: new Rules(), // 验证
      searchTime: [], // 创建日期
      dialogVisible: false, // 加载样式
      name: '', // 类型名称
      dialogTit: '', // 弹窗名称
      list: [], // 列表
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        multiple: true,
        // checkStrictly: true,
        emitPath: false
      },

      loading: false,
      passwordType: 'password',
      tableHeight: 200
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },

  mounted() {
    this.getSearchQuery('search');
    this.getOptions();
    // 初始化表格高度
    this.$nextTick(() => {
      this.initTableHeight();
    });
    window.addEventListener('resize', this.initTableHeight);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.initTableHeight);
  },
  methods: {
    // 初始化表格高度
    initTableHeight() {
      if (!this.$refs.dragTable) {
        this.$nextTick(() => {
          this.initTableHeight();
        });
        return;
      }
      const tableHeight = window.innerHeight - this.$refs.dragTable.$el.getBoundingClientRect().top - 70;
      this.tableHeight = Math.max(tableHeight, 200);
    },
    async getOptions(deptList) {
      try {
        const dept = await getDeptTree({
          withOutAutoCreate: false
        });
        this.options.dept = dept ? this.getTreeData(dept.data) : {};
      } catch (e) {
        this.options.dept = [];
      }
      this.getList();
    },
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // 最后一级没有数据将children变成undefined
          data[i].children = undefined;
        } else {
          // children不为空时继续调用该方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    async getList(tag) {
      this.setSearchQuery('search');
      if (tag != 'page') {
        this.page.pageNum = 1;
      }
      this.search.pageSize = this.search.pageSize || 30;
      try {
        this.loading = true;
        this.list = [];
        const { data } = await userList({
          pageNum: this.page.pageNum,
          ...this.search,
          pageSize: this.search.pageSize || 30
        });
        this.list = data.list;
        this.page.total = data.total;
        this.list.forEach(item => {
          item['deptName'] = [];
          item.deptList.forEach(val => {
            item.deptName.push(val.name);
          });
          item['roleName'] = [];
          item.roleList.forEach(val => {
            item.roleName.push(val.name);
          });
        });
        this.loading = false;
        // console.log(this.list);
      } catch (e) {
        this.page.total = 0;
        this.list = [];
        this.loading = false;
      }
    },
    // 搜索重置
    searchReset() {
      this.search = new Search();
      this.searchTime = [];
      this.getList();
    },
    // 创建时间
    changeDateRange(val) {
      this.search.startTime = val ? val[0] : '';
      this.search.endTime = val ? val[1] : '';
      this.getList();
    },
    // 切换密码显示隐藏
    showPwd(type) {
      if (this.passwordType === 'password') {
        this.passwordType = '';
      } else {
        this.passwordType = 'password';
      }
      // if (type == 'passwd') {
      //   this.$nextTick(() => {
      //     this.$refs.passwd.focus();
      //   });
      // } else {
      //   this.$nextTick(() => {
      //     this.$refs.repasswd.focus();
      //   });
      // }
    },
    // 详情跳转
    detailBtn(nameType, row) {
      this.$router.push({
        path: '/jurisdiction/account/detail',
        query: { nameType: nameType, id: row.id }
      });
    },
    // 操作按钮
    handleCommand(type, row) {
      switch (type) {
        case '修改':
          this.detailBtn('修改', row);
          break;
        case '禁用':
          this.hint('disable', '禁用该账号', row);
          break;
        case '启用':
          this.hint('enable', '启用该账号', row);
          break;
        case '删除':
          this.hint('del', '删除该账号', row);
          break;
        case '详情':
          this.detailBtn('详情', row);
          break;
        case '开启':
          this.hint('开启', '开启陌生设备', row);
          break;
        case '关闭':
          this.hint('关闭', '关闭陌生设备', row);
          break;
        case '重置密码':
          this.dialogVisible = true;
          this.dialogTit = '重置密码';
          this.detail = new Detail();
          this.detail.userId = row.id;
          break;
      }
    },
    // 提交密码
    createDetail(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.detail.passwd != this.detail.rePasswd) {
            this.$message({
              message: '警告,两次输入密码不一样哦~',
              type: 'warning'
            });
          } else {
            this.hint('dict', this.dialogTit);
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 确认提示
    hint(status, hintText, row) {
      this.$confirm(`${hintText}, 是否确认?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          switch (status) {
            case 'disable':
              this.stateChange(row);
              break;
            case 'enable':
              this.stateChange(row);
              break;
            case 'del':
              this.delRow(row);
              break;
            case 'dict':
              this.submitPass();
              break;
            case '开启':
              this.submitBrand('开启', row);
              break;
            case '关闭':
              this.submitBrand('关闭', row);
              break;
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 状态更改
    async stateChange(row) {
      let state = row.state == 0 ? 1 : 0;
      const res = await enableUser({
        state: state,
        id: row.id
      });
      this.$notification('操作成功', 'success', res.msg);
      this.getList();
    },
    async delRow(row) {
      const res = await deleteUser({
        id: row.id
      });
      this.$notification('操作成功', 'success', res.msg);
      this.getList();
    },
    // 重置密码
    async submitPass(row) {
      const res = await resetUserPasswd({
        ...this.detail
      });
      this.$notification('操作成功', 'success', res.msg);
      this.dialogVisible = false;
      this.getList();
    },
    // 开启/关闭验证陌生设备
    async submitBrand(type, row) {
      const res = await updateCheckDevice({
        id: row.id,
        isCheckUnknownDevice: type == '开启'
      });
      this.$notification('操作成功', 'success', res.msg);
      this.getList();
      // console.log(res);
    }

  }
};
</script>

<style lang="scss" scoped>
.content {
  // height: calc(100% - 56px);
  // overflow-y: hidden;
  // height: 85vh;
  ::v-deep img {
    width: 50px;
    border-radius: 4px;
    margin-top: 6px;
  }
}
.content:hover {
  overflow-y: auto;
}
.show-pwd {
  position: absolute;
  right: 15px;
  top: 52%;
  transform: translateY(-52%);
  font-size: 18px;
  color: #ccc;
  cursor: pointer;
  user-select: none;
  display: flex;
}
.svg-icon {
  font-size: 14px;
}
</style>
